package com.a0soft.gphone.aTruffleHog.wnd.info;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Comparator;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.widget.Toast;

import com.a0soft.gphone.aTruffleHog.R;
import com.a0soft.gphone.aTruffleHog.di.DeviceInfo;
import com.a0soft.gphone.aTruffleHog.di.DeviceInfoKey;
import com.a0soft.gphone.aTruffleHog.util.CONSTS;

public class SendDevInfoByMail {
    private static boolean m_bSending;
    
    public static void
    Send(Context ctx)
    {
        if (m_bSending)
            return;
        
        m_bSending = true;
        new SendDevInfoByMailTask(ctx, DeviceInfo.GetInstance(ctx)).execute();
    }
    
    ////////////////////////////////////////////
    private static class SendDevInfoByMailTask extends AsyncTask<Void, Void, String>
                                       implements Comparator<Field> {
        private static final String SYMB_LINE_BREAK = "\n";
        private static final String SYMB_CATE = "========";
        private static final String SYMB_AFTER_KEY = ":\n  ";
        private static final String KEY_INK = "AP_INK_";
        private static final String KEY_CAM = "CA_";
        private static final String KEY_CPU = "CP_";
        private static final String KEY_DISP = "DP_";
        private static final String KEY_MEM = "MI_";
        private static final String KEY_STOR = "SG_";
        private static final String KEY_SENS = "SS_";
        private static final String KEY_SYS = "ST_";
        private static final String KEY_TEL = "TP_";
        private static final String KEY_USER = "UR_";
        private static final String KEY[] = {
            KEY_CAM,    //0 at info_indicator in res/values/strings.xml     
            KEY_CPU,    //1 at info_indicator in res/values/strings.xml
            KEY_DISP,   //2 at info_indicator in res/values/strings.xml
            KEY_MEM,    //3 at info_indicator in res/values/strings.xml
            KEY_STOR,   //4 at info_indicator in res/values/strings.xml   
            KEY_SENS,   //5 at info_indicator in res/values/strings.xml   
            KEY_SYS,    //6 at info_indicator in res/values/strings.xml
            KEY_TEL,    //7 at info_indicator in res/values/strings.xml
            KEY_USER,   //8 at info_indicator in res/values/strings.xml
            KEY_INK     //Not located at info_indicator in res/values/strings.xml
        };
        private Context m_ctx = null;
        private DeviceInfo m_di = null;
    
        protected 
        SendDevInfoByMailTask(Context ctx, DeviceInfo di)
        {
            m_ctx = ctx;
            m_di = di;
        }
    
        @Override
        public int compare(Field o1, Field o2) {
            int returnVal = 0;
            //Check if field is valid
            if((o1 == null) ||
                    !String.class.equals(o1.getType()))
                returnVal = (((o2 == null) || 
                        !String.class.equals(o2.getType()))? 0: 1);
            else if((o2 == null) || 
                    !String.class.equals(o2.getType()))
                returnVal = -1;
            //Compare by field name
            else
                returnVal = o1.getName().compareToIgnoreCase(o2.getName());
            return returnVal;
        }
    
        @Override protected String 
        doInBackground(Void... params)
        {
            StringBuilder szDi = null;
            Field[] oKeys = null;
            if ((m_ctx != null) && (m_di != null) && m_di.IsReady() &&
                ((oKeys = DeviceInfoKey.K.class.getFields()) != null) &&
                (oKeys.length > 0)) {
                String szTypeName[] = m_ctx.getResources()
                                           .getStringArray(R.array.info_indicator);
                String szType = null;
                Arrays.sort(oKeys, this);
                szDi = new StringBuilder(8192);
    
                // Handle field of keys one by one
                for (Field oItm : oKeys) {
                    int iType = -1;
                    String szName = oItm.getName();
                    String szKey = null;
                    String szVal = null;
    
                    // Get key
                    try {
                        Object oKey = null;
                        szKey = (((oKey = oItm.get(null)) != null) ? oKey.toString()
                                                                   : null);
                    }
                    catch (Exception ex) {
                        continue;
                    }
    
                    // Skip if value not valid
                    if (szKey == null ||
                        !m_di.HasKey(szKey) || 
                        TextUtils.isEmpty(szVal = m_di.GetString(szKey)) ||
                        CONSTS.UNAVAILABLE.equalsIgnoreCase(szVal))
                        continue;
                    
                    // Check field category
                    else if ((szType == null) || !szName.startsWith(szType)) {
                        szType = null;
                        for (int a = KEY.length - 1; a >= 0; a--) {
                            if (szName.startsWith(KEY[a])) {
                                szType = KEY[a];
                                iType = a;
                                break;
                            }
                        }
                    }
    
                    // Skip item for application information
                    if (KEY_INK.equals(szType))
                        continue;
                    // Append human-readable category name
                    else if ((iType >= 0) && (iType < szTypeName.length)) {
                        szDi.append(SYMB_LINE_BREAK);
                        szDi.append(SYMB_LINE_BREAK);
                        szDi.append(SYMB_CATE);
                        szDi.append(szTypeName[iType]);
                        szDi.append(SYMB_CATE);
                    }
    
                    // Append key and value
                    szDi.append(SYMB_LINE_BREAK);
                    szDi.append(DeviceInfoKey.GetName(szKey));
                    szDi.append(SYMB_AFTER_KEY);
                    szDi.append(szVal);
                }
                
                szDi.append(SYMB_LINE_BREAK).append(SYMB_LINE_BREAK)
                    .append(SYMB_CATE).append(SYMB_LINE_BREAK);
                szDi.append(m_ctx.getString(R.string.di_mail_content_footer, 
                            m_ctx.getString(R.string.app_name)));
            }
            return (((szDi != null) && (szDi.length() > 0)) ? szDi.toString()
                                                           : null);
        }
    
        @Override protected void 
        onPreExecute()
        {
            Toast.makeText(m_ctx, R.string.wait, Toast.LENGTH_SHORT).show();
        }
    
        @Override protected void 
        onPostExecute(String strBody)
        {
            m_bSending = false;
            
            try {
                //Intent it = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:"));
                Intent it = new Intent(Intent.ACTION_SEND);
                it.putExtra(Intent.EXTRA_SUBJECT, 
                            m_ctx.getString(R.string.di_mail_subject));
                it.putExtra(Intent.EXTRA_TEXT, strBody);   
                it.setType("text/plain");
                m_ctx.startActivity(it);
            }
            catch (ActivityNotFoundException e) {
                new AlertDialog.Builder(m_ctx)
                               .setTitle(R.string.error)
                               .setIcon(android.R.drawable.ic_dialog_alert)
                               .setMessage(R.string.di_mail_no_client)
                               .setPositiveButton(android.R.string.ok, null)
                    .show();
            }
        }
    }
}